//
//  KKNetworking.m
//  XiaoShi
//
//  Created by leo on 2017/6/15.
//  Copyright © 2017年 liaozhenming. All rights reserved.
//

#import "KKNetworking.h"
#import "NSObject+Function.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"
#import "KKNetworkRequest.h"


@implementation KKNetworking

+ (void)sendRequest:(KKNetworkRequest*)networkRequest responseCallBack:(KKNetworkingResponseBlockHandle)callBack {
    [self sendRequest: networkRequest showStatus: false responseCallBack: callBack];
}

+ (void)sendRequest:(KKNetworkRequest*)networkRequest showStatus:(BOOL)showStatus responseCallBack:(KKNetworkingResponseBlockHandle)callBack {
    if (showStatus) {
//        [SVProgressHUD showWithStatus: @"提交中..."];
    }
    
    NSMutableURLRequest *request = nil;
    switch (networkRequest.methodType) {
        case KKNetworkRequestMethodType_Get:
        {
            NSString *requestURL = [[NSString stringWithFormat: @"%@?%@",networkRequest.requestURL, networkRequest.requestParmeterString] stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
            request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: requestURL]];
            [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
            [request setTimeoutInterval: 15.0];
            [request setHTTPMethod: @"GET"];
        }
            break;
        case KKNetworkRequestMethodType_Post:
        {
            NSString *requestURL = [networkRequest.requestURL stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
            request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: requestURL]];
            [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
            [request setTimeoutInterval: 15.0];
            [request setHTTPMethod: @"POST"];
            [request setHTTPBody: networkRequest.requestPostData];
        }
            break;
        case KKNetworkRequestMethodType_Put:
        {
            NSString *requestURL = [networkRequest.requestURL stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
            request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: requestURL]];
//            [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
            [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
            [request setTimeoutInterval: 15.0];
            [request setHTTPMethod: @"PUT"];
            [request setHTTPBody: networkRequest.requestPostData];
        }
            break;
        case KKNetworkRequestMethodType_Delete:
        {
            NSString *requestURL = [[NSString stringWithFormat: @"%@?%@",networkRequest.requestURL, networkRequest.requestParmeterString] stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
            request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: requestURL]];
            [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
            [request setTimeoutInterval: 15.0];
            [request setHTTPMethod: @"DELETE"];
        }
            break;
        default:
            break;
    }
    
    if (KKUser.ticket) {
        [request addValue: KKUser.ticket forHTTPHeaderField: @"ticket"];
    }
    
    if (DEBUG) {
        
        NSLog(@"请求接口 = %@", request.URL);
        if (networkRequest.methodType == KKNetworkRequestMethodType_Post || networkRequest.methodType == KKNetworkRequestMethodType_Put) {
            NSLog(@"请求参赛 = %@", networkRequest.requestParmeters);
        }
    }
    
    [self private_sendRequest: request responseClassName: networkRequest.responseClassString responseCallBack: callBack];
}

+ (void)uploadImage:(UIImage*)image parmeters:(NSDictionary*)parmeters responseCallBack:(KKNetworkingResponseBlockHandle)callBack {
    //  上传图片
    [self uploadImage: image parmeters: parmeters progress: nil responseCallBack:callBack];
}

+ (void)uploadImage:(UIImage*)image parmeters:(NSDictionary*)parmeters progress:(KKNetworkingProgressBlockHandle)progress responseCallBack:(KKNetworkingResponseBlockHandle)callBack {
    
    if (progress == nil) {
//        [SVProgressHUD showWithStatus: @"提交中..."];
    }
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *url = [NSString stringWithFormat: @"%@/assets", APP_Request_BasicURLString];
    NSString *requestURL = [url stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
//    if (KKUser.ticket) {
//        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//        [manager.requestSerializer setValue: KKUser.ticket forHTTPHeaderField: @"ticket"];
//    }
    
    [manager POST: requestURL parameters: nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData: imageData name: @"image" fileName: @"image.jpg" mimeType: @"image/jpeg"];
    } progress: ^(NSProgress * _Nonnull uploadProgress) {
        if (progress != nil) {
            
            float progressValue = (uploadProgress.completedUnitCount * 0.1) / (uploadProgress.totalUnitCount * 0.1);
            
            progress (progressValue);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *errorString = nil;
        id responseResult = nil;
        if ([responseObject isKindOfClass: [NSDictionary class]]) {
            NSDictionary *responseDictionary = (NSDictionary*)responseObject;
            
            NSString *err = responseDictionary[@"err"];
            if (err == nil || [err isKindOfClass: [NSNull class]]) {
                responseResult = responseDictionary[@"path"];
            }
            else {
                errorString = err;
            }
        }
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
            [SVProgressHUD dismiss];
            if (callBack) {
                callBack(responseResult, errorString);
            }
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
            [SVProgressHUD showErrorWithStatus: @"请求超时，请稍后再试～"];
            
            
            
            if (callBack) {
                callBack(nil, error.localizedDescription);
            }
        }];
    }];
    return;
}

#pragma mark - Private methods

+ (void)private_sendRequest:(NSURLRequest*)request responseClassName:(NSString*)className responseCallBack:(KKNetworkingResponseBlockHandle)callBack {
    
    if (request == nil) {
        if (callBack) {
             callBack(nil, @"请求出错");
        }
        return;
    }
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: true];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest: request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSString *errorString = error.localizedDescription;
        NSError *responseError;
        id responseObject = nil;
        
        if (DEBUG) {
            NSString *responseString = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
            NSLog(@"请求返回值 = %@", responseString);
        }
        
        if (error== nil && data != nil) {
            
            NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &responseError];
            if (responseError) {
                errorString = responseError.localizedDescription;
            }
            else {
                
                NSString *err = responseDictionary[@"err"];
                if (err == nil || [err isKindOfClass: [NSNull class]]) {
                    responseObject = responseDictionary[@"result"];
                    if (className) {
                        //  设定了返回值的类型对象，需要进行解析对象
                        id result = responseObject;
                        Class class = NSClassFromString(className);
                        if ([result isKindOfClass: [NSDictionary class]]) {
                            id object = [class new];
                            [object kk_parserJsonDictionary: result];
                            responseObject = object;
                        }
                        else if ([result isKindOfClass: [NSArray class]]) {
                            
                            NSMutableArray *itemArray = [NSMutableArray array];
                            for (NSDictionary *resultItem in (NSArray*)result) {
                                id object = [class new];
                                [object kk_parserJsonDictionary: resultItem];
                                [itemArray addObject: object];
                            }
                            responseObject = itemArray;
                        }
                    }
                }
                else {
                    errorString = err;
                }
            }
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
                [SVProgressHUD dismiss];
                if (callBack) {
                    callBack(responseObject, errorString);
                }
            }];
        }
        else {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
                [SVProgressHUD showErrorWithStatus: @"请求超时，请稍后再试～"];
                if (callBack) {
                    callBack(responseObject, errorString);
                }
            }];
        }
    }];
    [dataTask resume];
}

@end
